<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>记忆配对</title>
  <!-- 引入Tailwind CSS和Font Awesome -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  
  <!-- 配置Tailwind自定义主题 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#4F46E5', // 主色调：紫色
            secondary: '#EC4899', // 辅助色：粉色
            dark: '#1F2937', // 深色背景
            light: '#F9FAFB' // 浅色文本
          }
        }
      }
    }
  </script>
  
  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      /* 卡片翻转效果基础样式 */
      .card-flip {
        perspective: 1000px;
        transform-style: preserve-3d;
      }
      
      /* 卡片正反两面共同样式 */
      .card-front, .card-back {
        backface-visibility: hidden;
        transition: transform 0.6s;
      }
      
      /* 卡片背面初始旋转180度 */
      .card-back { transform: rotateY(180deg); }
      
      /* 卡片翻转时的正面样式 */
      .card-flipped .card-front { transform: rotateY(180deg); }
      
      /* 卡片翻转时的背面样式 */
      .card-flipped .card-back { transform: rotateY(0deg); }
      
      /* 卡片匹配成功时的动画效果 */
      .card-matched { animation: matched 0.5s ease-in-out; }
      @keyframes matched {
        0%, 100% { transform: scale(1); }
        50% { transform: scale(1.05); box-shadow: 0 0 15px theme('colors.primary'); }
      }
    }
  </style>
</head>
<body class="bg-dark text-light min-h-screen flex flex-col items-center p-4">
  <!-- 游戏标题 -->
  <h1 class="text-[clamp(1.5rem,4vw,2.5rem)] font-bold text-gradient-to-r from-primary to-secondary mb-6">记忆配对</h1>
  
  <!-- 游戏状态面板 -->
  <div class="flex justify-between w-full max-w-md mb-4">
    <div class="flex items-center">
      <i class="fa fa-clock-o text-primary mr-2"></i>
      <span id="timer">00:00</span> <!-- 计时器显示 -->
    </div>
    <div class="flex items-center">
      <i class="fa fa-refresh text-secondary mr-2"></i>
      <span id="moves">0</span> <!-- 移动步数显示 -->
    </div>
    <button id="reset" class="bg-primary hover:bg-primary/80 text-white px-4 py-1 rounded transition-colors">
      重置 <!-- 重置游戏按钮 -->
    </button>
  </div>
  
  <!-- 游戏卡片容器 -->
  <div id="game" class="grid grid-cols-4 gap-3 w-full max-w-md"></div>
  
  <!-- 游戏结束模态框 -->
  <div id="modal" class="fixed inset-0 bg-black/70 flex items-center justify-center hidden">
    <div class="bg-dark p-6 rounded-lg text-center">
      <h2 id="modal-title" class="text-xl font-bold mb-2">恭喜！</h2>
      <p id="modal-message" class="mb-4">你完成了游戏</p>
      <button id="play-again" class="bg-primary hover:bg-primary/80 text-white px-6 py-2 rounded transition-colors">
        再玩一次 <!-- 重新开始游戏按钮 -->
      </button>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // 游戏图标库 - 用于卡片匹配
      const icons = ['fa-heart', 'fa-star', 'fa-diamond', 'fa-bolt', 'fa-leaf', 
                     'fa-car', 'fa-plane', 'fa-rocket', 'fa-tree', 'fa-coffee'];
      
      // 游戏状态管理
      let gameState = {
        cards: [], // 存储所有卡片信息
        flipped: [], // 当前翻转的卡片索引
        matched: 0, // 已匹配的卡片对数
        moves: 0, // 玩家移动次数
        timer: 0, // 游戏时间（秒）
        interval: null, // 计时器间隔引用
        started: false // 游戏是否已开始
      };

      // DOM元素引用
      const gameEl = document.getElementById('game'); // 游戏容器
      const timerEl = document.getElementById('timer'); // 计时器元素
      const movesEl = document.getElementById('moves'); // 步数元素
      const resetBtn = document.getElementById('reset'); // 重置按钮
      const modal = document.getElementById('modal'); // 模态框
      const modalTitle = document.getElementById('modal-title'); // 模态框标题
      const modalMessage = document.getElementById('modal-message'); // 模态框消息
      const playAgainBtn = document.getElementById('play-again'); // 再玩一次按钮

      // 初始化游戏
      function init() {
        gameEl.innerHTML = ''; // 清空游戏容器
        
        // 重置游戏状态
        gameState = {
          cards: [], flipped: [], matched: 0, moves: 0, timer: 0, interval: null, started: false
        };
        
        // 重置UI显示
        movesEl.textContent = '0';
        timerEl.textContent = '00:00';

        // 设置游戏卡片（8对16张）
        const pairs = 8;
        const selectedIcons = icons.slice(0, pairs);
        const allIcons = [...selectedIcons, ...selectedIcons]; // 复制一份形成配对
        const shuffledIcons = allIcons.sort(() => Math.random() - 0.5); // 随机打乱图标

        // 创建卡片元素并添加到游戏容器
        shuffledIcons.forEach((icon, index) => {
          const card = createCard(icon, index);
          gameEl.appendChild(card);
          gameState.cards.push({ icon, matched: false, element: card });
        });
      }

      // 创建单个卡片元素
      function createCard(icon, index) {
        const card = document.createElement('div');
        card.className = 'card-flip cursor-pointer relative aspect-square rounded-lg overflow-hidden shadow-md';
        card.dataset.index = index; // 存储卡片索引

        // 设置卡片正反两面内容
        card.innerHTML = `
          <div class="card-front absolute inset-0 bg-gray-700 flex items-center justify-center">
            <i class="fa fa-question text-2xl text-gray-400"></i> <!-- 卡片正面显示问号 -->
          </div>
          <div class="card-back absolute inset-0 bg-gradient-to-br from-primary to-secondary flex items-center justify-center">
            <i class="fa ${icon} text-2xl text-white"></i> <!-- 卡片背面显示图标 -->
          </div>
        `;

        // 添加点击事件
        card.addEventListener('click', () => handleClick(index));
        return card;
      }

      // 处理卡片点击事件
      function handleClick(index) {
        const card = gameState.cards[index];
        
        // 忽略已匹配或已翻转的卡片，以及已经翻开两张卡片的情况
        if (card.matched || gameState.flipped.length >= 2 || gameState.flipped.includes(index)) return;

        // 如果游戏还未开始，启动计时器
        if (!gameState.started) {
          gameState.started = true;
          gameState.interval = setInterval(() => {
            gameState.timer++;
            const mins = Math.floor(gameState.timer / 60).toString().padStart(2, '0');
            const secs = (gameState.timer % 60).toString().padStart(2, '0');
            timerEl.textContent = `${mins}:${secs}`;
          }, 1000);
        }

        // 翻转卡片并记录
        flipCard(index);
        gameState.flipped.push(index);

        // 如果翻开了两张卡片，检查是否匹配
        if (gameState.flipped.length === 2) {
          gameState.moves++;
          movesEl.textContent = gameState.moves;
          setTimeout(checkMatch, 800); // 延迟检查，让玩家看到两张卡片
        }
      }

      // 翻转卡片
      function flipCard(index) {
        gameState.cards[index].element.classList.add('card-flipped');
      }

      // 检查两张卡片是否匹配
      function checkMatch() {
        const [i1, i2] = gameState.flipped;
        const card1 = gameState.cards[i1];
        const card2 = gameState.cards[i2];

        if (card1.icon === card2.icon) {
          // 卡片匹配成功
          card1.matched = true;
          card2.matched = true;
          card1.element.classList.add('card-matched');
          card2.element.classList.add('card-matched');
          gameState.matched++;

          // 检查游戏是否结束
          if (gameState.matched === 8) {
            clearInterval(gameState.interval); // 停止计时器
            setTimeout(showModal, 500); // 显示游戏结束模态框
          }
        } else {
          // 卡片不匹配，翻回
          card1.element.classList.remove('card-flipped');
          card2.element.classList.remove('card-flipped');
        }

        // 重置已翻转的卡片数组
        gameState.flipped = [];
      }

      // 显示游戏结束模态框
      function showModal() {
        modalTitle.textContent = '恭喜！';
        modalMessage.textContent = `你用了 ${gameState.moves} 步和 ${gameState.timer} 秒完成了游戏！`;
        modal.classList.remove('hidden');
      }

      // 重置游戏
      function resetGame() {
        clearInterval(gameState.interval); // 清除计时器
        modal.classList.add('hidden'); // 隐藏模态框
        init(); // 重新初始化游戏
      }

      // 事件监听器
      resetBtn.addEventListener('click', resetGame);
      playAgainBtn.addEventListener('click', resetGame);

      // 初始化游戏
      init();
    });
  </script>
</body>
</html>
    